#include "Downloader.h"
#include <QMessageBox>
#include <QFileDialog>

Downloader::Downloader(QWidget *parent)
    : QWidget(parent)
{
    ui.setupUi(this);
    m_pDownloader = new httpDownload();
    connectSigSlot();
}

Downloader::~Downloader()
{
    if (m_pDownloader) {
        m_pDownloader->cancel();
        m_pDownloader->deleteLater();
        m_pDownloader = nullptr;
    }
}

void Downloader::slotProgress(qint64 bytesReceived, qint64 bytesTotal, const QString& strSpeed)
{
    if (bytesReceived == 0 && bytesReceived == 0)
        return;
    ui.progressBar->setMaximum(bytesTotal);
    ui.progressBar->setValue(bytesReceived);
    ui.label->setText(strSpeed);
}

void Downloader::slotDownloadErorr(const QString& errStr)
{
    QMessageBox::warning(this, QStringLiteral("Error"), QStringLiteral("file download failed: %1").arg(errStr), QMessageBox::Yes);
}

void Downloader::slotStartDownload()
{
    qDebug() << "UI start download";
}

void Downloader::slotDownloadFinished()
{
    QMessageBox::information(this, QStringLiteral("HAHA"), QStringLiteral("file download success!"), QMessageBox::Yes);
}

void Downloader::connectSigSlot()
{
    connect(m_pDownloader, &httpDownload::sigErorr, this, &Downloader::slotDownloadErorr);
    connect(m_pDownloader, &httpDownload::sigStartDownload, this, &Downloader::slotStartDownload);
    connect(m_pDownloader, &httpDownload::sigProgress, this, &Downloader::slotProgress);
    connect(m_pDownloader, &httpDownload::sigFinished, this, &Downloader::slotDownloadFinished);
    connect(ui.pushButton_2, &QPushButton::clicked, [this]() {
        m_dir = QFileDialog::getExistingDirectory(this, "select dir", "");
    });
    connect(ui.pushButton, &QPushButton::clicked, [this]() {
        m_pDownloader->download(ui.lineEdit->text(), m_dir);
    });
}
